{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "07bfe930",
   "metadata": {},
   "source": [
    "# API 文档介绍（Face++ API）\n",
    "* 本周主要内容：图像识别（认知服务）\n",
    "* 22春_API_人工智能与机器学习_week05\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21b9f549",
   "metadata": {},
   "source": [
    "# 百度AI开放平台\n",
    "\n",
    "## 通用物体和场景识别\n",
    "\n",
    "### 1.鉴权认证机制(access_token)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "5dcb3ead",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.979b8a9a3c25b2ef72316a03c93f4ed1.315360000.1964436220.282335-25904783', 'expires_in': 2592000, 'session_key': '9mzdCuYSQ0DA2NuOzSy8ugJhVoUqpBmhl41PwLfmUXJdN+fslo9cHeqav3ndaZ1aFx1lZDerwqS78hD2wx9S7isXzvC8QQ==', 'access_token': '24.1b07c48c92aa50165c3d313f703f201f.2592000.1651668220.282335-25904783', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '208492421802e85baa17f5977cd2bbe7'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=bVTj7Ilx8Gfg0bTIlPPaxUGg&client_secret=xsRtpFBmQVSA5nvzvGqRaI52qgIQBtkr'\n",
    "\n",
    "# 准备URL参数\n",
    "\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'bVTj7Ilx8Gfg0bTIlPPaxUGg',\n",
    "    'client_secret':'xsRtpFBmQVSA5nvzvGqRaI52qgIQBtkr'\n",
    "}\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "97559d75",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.1b07c48c92aa50165c3d313f703f201f.2592000.1651668220.282335-25904783'"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "access_token = response.json()['access_token']\n",
    "access_token"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f299c2af",
   "metadata": {},
   "source": [
    "## 1、通用物体和场景识别\n",
    "\n",
    "* 接口描述\n",
    "\n",
    "> 该请求用于通用物体及场景识别，即对于输入的一张图片（可正常解码，且长宽比适宜），输出图片中的多个物体及场景标签。\n",
    "\n",
    "* HTTP方法\n",
    "\n",
    "> POST\n",
    "\n",
    "* 请求URL\n",
    "\n",
    ">  https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\n",
    "\n",
    "* 请求参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "d3ef2cba",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "311914bf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[             参数                                                  值\n",
       " 0  access_token  通过API Key和Secret Key获取的access_token,参考“Access ...,\n",
       "              参数                                  值\n",
       " 0  Content-Type  application/x-www-form-urlencoded,\n",
       "           参数       是否必选       类型 可选值范围  \\\n",
       " 0      image    和url二选一   string     -   \n",
       " 1        url  和image二选一   string     -   \n",
       " 2  baike_num          否  integer     -   \n",
       " \n",
       "                                                   说明  \n",
       " 0  图像数据，base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边...  \n",
       " 1  图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4...  \n",
       " 2                                   返回百科信息的结果数，默认不返回  ,\n",
       "               字段 是否必选             类型                               说明\n",
       " 0         log_id    是         uint64                 唯一的log id，用于问题定位\n",
       " 1     result_num    是         unit32  返回结果数目，及result数组中的元素个数，最多返回5个结果\n",
       " 2         result    是  arrry(object)                           标签结果数组\n",
       " 3       +keyword    是         string                      图片中的物体或场景名称\n",
       " 4         +score    是          float                          置信度，0-1\n",
       " 5          +root    是         string   识别结果的上层标签，有部分钱币、动漫、烟酒等tag无上层标签\n",
       " 6    +baike_info    否         object                    对应识别结果的百科词条名称\n",
       " 7    ++baike_url    否         string                   对应识别结果百度百科页面链接\n",
       " 8    ++image_url    否         string                     对应识别结果百科图片链接\n",
       " 9  ++description    否         string                     对应识别结果百科内容描述]"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_html('https://ai.baidu.com/ai-doc/IMAGERECOGNITION/Xk3bcxe21')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "895177c1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.5fc47f9de81daa38bdeaa71e05bc5f8d.315360000.1964436242.282335-25904783', 'expires_in': 2592000, 'session_key': '9mzdWBPzwmscgRB80nnQ0vQjw4anUubRJa3fhINwL43J9Rl00PlAK0Q56YcyPpOUfcx4vwCgl4c/CprLLVHBv98GfkbQFQ==', 'access_token': '24.ccad0ed74ce9e4dddc1f884fd5b9de24.2592000.1651668242.282335-25904783', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '3d4b29d3f48dea4f3b50d1e30b4fe1f4'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=bVTj7Ilx8Gfg0bTIlPPaxUGg&client_secret=xsRtpFBmQVSA5nvzvGqRaI52qgIQBtkr'\n",
    "\n",
    "# 准备URL参数\n",
    "\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'bVTj7Ilx8Gfg0bTIlPPaxUGg',\n",
    "    'client_secret':'xsRtpFBmQVSA5nvzvGqRaI52qgIQBtkr'\n",
    "}\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "response = requests.get(host)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "09e7a0f9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.ccad0ed74ce9e4dddc1f884fd5b9de24.2592000.1651668242.282335-25904783'"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "access_token = response.json()['access_token']\n",
    "access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "a98bf1ee",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '美女', 'score': 0.888889, 'root': '人物-人物特写', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%BE%8E%E5%A5%B3/109596', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/91529822720e0cf3acdfc0280046f21fbe09aa3d', 'description': '美女，汉语词语，拼音是měi nǚ，意思是容貌姣好、仪态优雅的女子。'}}, {'keyword': '女人', 'score': 0.559721, 'root': '人物-人物特写', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%A5%B3%E4%BA%BA/18439', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/e824b899a9014c08813034cd0c7b02087bf4f44b', 'description': '女人同男人相对，从生理学上讲，具有xx染色体的人就是女人，在生理上具有区别于男人的特征，如具有女性生殖系统。从动物学上讲，女人即为雌性的人类。'}}, {'keyword': '人物特写', 'score': 0.377728, 'root': '人物-人物特写', 'baike_info': {}}, {'keyword': '头发', 'score': 0.190792, 'root': '人物-人物特写', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%A4%B4%E5%8F%91/84388', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b21bb051f8198618bbe5afb540ed2e738bd4e665', 'description': '头发，指生长在头部的毛发。头发并不是器官，所以不含神经,血管，但含有细胞。头发主要用于保护头部。细软蓬松的头发具有弹性，可以抵挡较轻的碰撞，还可以帮助头部汗液的蒸发。一般人的头发约有10万根，在所有毛发中，头发的长度最长，尤其是女子留长发者。有的可长到95～100cm，甚至150cm，但一般不会超出200cm。头发的颜色一般是由基因决定的，常见的有黑色、金黄色、棕色及红色等。当人类老化时，头发通常会变成银白色。由于种族和地区的不同，头发有乌黑、金黄、红褐、红棕、淡黄、灰白，甚至还有绿色和红色的。科学研究证明：头发的颜色同头发里所含的金属元素的不同有关。黑发含有等量的铜、铁,黑色素，当镍的含量增多时，就会变成灰白色。金黄色头发含有钛，红褐色头发含有钼，红棕色的除含铜、铁之外，还有钴，绿色头发则是含有过多的铜。在非洲一些国家，有些孩子的头发呈红色，这是严重缺乏蛋白质造成的。'}}, {'keyword': '红唇', 'score': 0.006016, 'root': '非自然图像-病理图', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%BA%A2%E5%94%87/2918462', 'description': '红唇服饰有限公司――集设计、生产、营销于一体的专业的女装公司；公司坐落于服饰名城虎门，创立于1997年。'}}], 'log_id': 1510961411600361492}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('D:/1111/api/week6/5.jpg', 'rb') # 绝对路径\n",
    "f = open('5.jpg','rb')# 相对路径\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# params = {\"imgae\":img}\n",
    "\n",
    "\n",
    "payload={\n",
    "    'access_token':access_token,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c2635d5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29d0bd25",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0fabf2f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
